//
//  YMNetworkVC.swift
//  swift_review
//
//  Created by Andrew on 2024/11/25.
//

import UIKit

class YMNetworkVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
    }
    
    func getRequest() {
        // 示例 URL 和参数
        let url = "https://jsonplaceholder.typicode.com/posts"
        let parameters = ["userId": 1]
        
        NetworkManager.request(urlString: url, method: .GET, parameters: nil) { result in
            switch result {
            case .success(let data):
                do {
                    //尝试解析json数据
                    if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] {
                        print("请求成功: \(json)")
                    }
                } catch {
                    print("JSON 解析错误: \(error)")
                }
            case .failure(let error):
                print("请求失败: \(error.localizedDescription)")
            }
        }
    }
    
    //发起post请求
    func postRequest() {
        // 示例 URL 和参数
        let url = "https://jsonplaceholder.typicode.com/posts"
        let parameters = ["userId": 1]
        
        NetworkManager.request(urlString: url, method: .POST, parameters: ["title": "foo"]) { result in
            switch result {
            case .success(let data):
                do {
                    // 尝试解析 JSON 数据
                    if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                        print("请求成功: \(json)")
                    }
                } catch {
                    print("JSON 解析错误: \(error)")
                }
            case .failure(let error):
                print("请求失败: \(error.localizedDescription)")
            }
        }
    }
    
    func jsonModel() {
        // 示例 URL
        let url = "https://jsonplaceholder.typicode.com/posts"

        // 调用封装方法
        NetworkHander.request(urlString: url, method: .GET, parameters: nil) { (result: Result<[Post], Error>) in
            switch result {
            case .success(let posts):
                // 解析成功，输出结果
                for post in posts {
                    print("Post ID: \(post.id), Title: \(post.title)")
                    print("Body: \(post.body)")
                }
            case .failure(let error):
                print("请求失败: \(error.localizedDescription)")
            }
        }
    }
}
